package com.fs.service;

import com.fs.controller.MainController;
import com.fs.model.*;
import com.fs.util.FATFactory;
import com.fs.util.FATUtil;
import com.fs.view.FileView;
import com.fs.view.PropertyView;
import com.fs.view.RenameView;
import com.fs.view.delView;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.FlowPane;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FATService {
    //文件分配表
    private FAT fat;
    private int nextName=6;//测试用的下一个文件名
    private int nextIndex=6;
    private DiskBlock[] diskBlocks;
    private List<Path> paths;
    public FATService(){
        fat= FATFactory.getFATInstance();
        diskBlocks=fat.getDiskBlocks();
        paths=fat.getPaths();
        paths.add(fat.getRootPath());
    }
    /**新建文件
     *recentPath  当前路径名
     */
    /*public void createFile(String recentPath) {
        System.out.println("文件创建在："+recentPath);
        //测试数据  将文件创建在recentPath当前路径下
        Path parentPath=null;
        for (Path path : fat.getPaths()) {
            if(path.getPathName().equals(recentPath)){
                parentPath=path;
                break;
            }
        }
        Folder parentFolder=fat.getFolder(recentPath);//获取新建文件夹所在目录

        File file1 = new File(nextName+"", recentPath, nextIndex, parentFolder);
        fat.getDiskBlocks()[nextIndex] = new DiskBlock(nextIndex, FATUtil.END, FATUtil.FILE, file1);
        fat.getDiskBlocks()[nextIndex].setBegin(true);

        //更新要展现的数据
        fat.initPresentBlockList(recentPath);
        nextIndex++;
        nextName++;

    }*/
    /*public void createFolder(String recentPath){
        //测试数据,需要保证路径名唯一、当前路径下文件名唯一、
        Path parentPath=null;
        for (Path path : fat.getPaths()) {
            if(path.getPathName().equals(recentPath)){
                parentPath=path;
                break;
            }
        }
        //查找该目录的父目录是否存在
        if(parentPath==null){
            //不存在，不能建立
            System.out.println("父目录不存在，创建失败");
        }
        //如果存在，查找是否存在同名目录
        //存在，不能建立
        //不存在，则查找一个空目录项，为该目录申请一个盘块，并填写目录内容。


        Folder parentFolder=fat.getFolder(recentPath);//获取新建文件夹所在目录

        String newPathName=null;
        if("C:".equals(recentPath)){
            newPathName=recentPath+"\\"+nextName;//在c中创建的时候要单独处理新建路径
        }else {
            newPathName=recentPath+ nextName;
        }
        Path path1 = new Path(newPathName, parentPath);
        parentPath.getChildren().add(path1);//加入到父路径集合中
        fat.getPaths().add(path1);//加入到路径集合中

        Folder folder1 = new Folder(nextName+"", recentPath, nextIndex,parentFolder);
        fat.getDiskBlocks()[nextIndex] = new DiskBlock(nextIndex, FATUtil.END, FATUtil.FOLDER, folder1);
        fat.getDiskBlocks()[nextIndex].setBegin(true);


        //更新要展现的数据
        fat.initPresentBlockList(recentPath);
        nextIndex++;
        nextName++;
    }*/


    /**
     * 在指定路径下创建文件夹
     * @param path
     * @return
     */
    public int createFolder(String path) {
        String folderName = null;
        boolean canName = true;
        int index = 1;
        // 得到文件夹名
        do {
            folderName = "文件夹";
            canName = true;
            folderName += index;
            for (int i = 2; i < diskBlocks.length; i++) {
                if (!diskBlocks[i].isFree()) {
                    if (diskBlocks[i].getType().equals(FATUtil.FOLDER)) {
                        Folder folder = (Folder) diskBlocks[i].getObject();
                        if (path.equals(folder.getLocation())) {
                            if (folderName.equals(folder.getFolderName())) {
                                canName = false;
                            }
                        }
                    }
                }
            }
            index++;
        } while (!canName);
        int index2 = searchEmptyDiskBlock();
        if (index2 == FATUtil.ERROR) {
            return FATUtil.ERROR;
        } else {
            Folder parent = getFolder(path);
            Folder folder = new Folder(folderName, path, index2, parent);
            if (parent instanceof Folder) {
                parent.addChildren(folder);
            }
            diskBlocks[index2].allocBlock(FATUtil.END, FATUtil.FOLDER, folder, true);
            Path parentP = getPath(path);
            Path thisPath = new Path(path + "\\" + folderName, parentP);
            if (parentP != null) {
                parentP.addChildren(thisPath);
            }
            paths.add(thisPath);
            folder.setPath(thisPath);
            System.out.println(thisPath.getPathName());
            System.out.println(thisPath);
        }
        fat.initPresentBlockList(path);
        return index2;
    }
    /**
     * 返回指定路径下所有文件夹
     * @param path
     * @return
     */
    public List<Folder> getFolders(String path) {
        List<Folder> list = new ArrayList<Folder>();
        for (int i = 2; i < diskBlocks.length; i++) {
            if (!diskBlocks[i].isFree()) {
                if (diskBlocks[i].getObject() instanceof Folder) {
                    if (((Folder) (diskBlocks[i].getObject())).getLocation().equals(path)) {
                        list.add((Folder) diskBlocks[i].getObject());
                    }
                }
            }
        }
        return list;
    }
    /**
     * 返回指定路径指向的文件夹
     * @param path
     * @return
     */
    public Folder getFolder(String path) {
        if (path.equals("C:")) {
            return fat.getC();
        }
        int split = path.lastIndexOf('\\');
        String location = path.substring(0, split);
        String folderName = path.substring(split + 1);
        List<Folder> folders = getFolders(location);
        for (Folder folder : folders) {
            if (folder.getFolderName().equals(folderName)) {
                return folder;
            }
        }
        return null;
    }
    /**
     * 给出路径名返回路径对象
     * @param path
     * @return
     */
    public Path getPath(String path) {
        for (Path p : paths) {
            if (p.getPathName().equals(path)) {
                return p;
            }
        }
        return null;
    }
    /**
     * 返回第一个空闲盘块的盘块号
     * @return
     */
    public int searchEmptyDiskBlock() {
        for (int i = 2; i < diskBlocks.length; i++) {
            if (diskBlocks[i].isFree()) {
                return i;
            }
        }
        return FATUtil.ERROR;
    }


    /**
     * 在指定路径下创建文件
     * @param path
     * @return
     */
    public int createFile(String path) {
        String fileName = null;
        boolean canName = true;
        int index = 1;
        // 得到文件名
        do {
            fileName = "文件";
            canName = true;
            fileName += index;
            for (int i = 2; i < diskBlocks.length; i++) {
                if (!diskBlocks[i].isFree()) {
                    if (diskBlocks[i].getType().equals(FATUtil.FILE)) {
                        File file = (File) diskBlocks[i].getObject();
                        if (path.equals(file.getLocation())) {
                            if (fileName.equals(file.getFileName())) {
                                canName = false;
                            }
                        }
                    }
                }
            }
            index++;
        } while (!canName);
        int index2 = searchEmptyDiskBlock();
        if (index2 == FATUtil.ERROR) {
            return FATUtil.ERROR;
        } else {
            Folder parent = getFolder(path);
            File file = new File(fileName, path, index2, parent);
            file.setFlag(FATUtil.FLAGWRITE);
            if (parent instanceof Folder) {
                parent.addChildren(file);
            }
            diskBlocks[index2].allocBlock(FATUtil.END, FATUtil.FILE, file, true);
        }
        fat.initPresentBlockList(path);

        return index2;
    }
    public void rename(List<DiskBlock> blockList, Label[] icons, Map<Path, TreeItem<String>> pathMap, int index){
        DiskBlock thisBlock = blockList.get(index);
        new RenameView(thisBlock, fat, icons[index], pathMap);
    }
    public void property(List<DiskBlock> blockList, Label[] icons, Map<Path, TreeItem<String>> pathMap, int index){
        DiskBlock thisBlock = blockList.get(index);
        new PropertyView(thisBlock, fat, icons[index], pathMap);
    }

}
